package com.fusion.core.comm.rpc;

import com.fusion.core.comm.Packet;
import com.fusion.core.comm.RPC;
import com.fusion.core.comm.T;

import java.io.*;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

/**
 * @author SwethaShivakumar 
 * Project: fusion
 * Date: Mar 9, 2009
 * URL: http://fusionwiki.co.cc
 * Mail Me At: shiva@fusionproject.co.cc
 */
public abstract class CompressedRPC extends RPC {
    public abstract void executeCompressed(DataInputStream in) throws IOException;
    public abstract void serializeCompressed(DataOutputStream out) throws IOException;

    public void execute(Packet data) throws IOException {
        int len = data.readInt();
        byte arr[] = new byte[len];
        data.readArray(arr);
        ByteArrayInputStream bais = new ByteArrayInputStream(arr);
        DataInputStream in = new DataInputStream(new InflaterInputStream(bais));

        executeCompressed(in);
        in.close();
    }

    public Packet serializeTo(Packet p) throws IOException {
        ByteArrayOutputStream buf = new ByteArrayOutputStream(1024); //in general compressed RPC are fairly big packets - that's why we crank up the starting byte array size
        DataOutputStream out = new DataOutputStream(new DeflaterOutputStream(buf, new Deflater(9)));

        serializeCompressed(out);

        out.flush();
        out.close();
        byte arr[] = buf.toByteArray();
        p.writeInt(arr.length);
        p.writeArray(arr);
        if(T.t)T.debug("Compressed RPC: from "+out.size()+" bytes to "+arr.length+" bytes.");
        return p;
    }
}
